package top.heue.utils.base.helper

import android.view.View

/**
 * 放在bean中的操作事件
 */
class ListenerHelper(block: ListenerHelper.() -> Unit) {

    init {
        block.invoke(this)
    }

    /** 参数存放*/
    private var params: List<Any> = listOf()

    private var onClickListener: OnClick? = null
    private var onLongClickListener: OnLongClick? = null

    /** 注册点击事件*/
    fun setOnClick(block: OnClick) {
        onClickListener = block
    }

    /** 注册长按事件一般是返回true*/
    fun setOnLongClick(block: OnLongClick) {
        onLongClickListener = block
    }

    /** 转为点击事件，无法传递额外参数*/
    fun asViewOnClickListener() = run {
        View.OnClickListener { v -> v?.let { onClick(it) } }
    }

    /** 转为长按事件，无法传递额外参数*/
    fun asViewOnLongClickListener() = run {
        View.OnLongClickListener { v -> v?.let { onLongClick(v) } ?: false }
    }

    /** 点击事件触发，后续可以自定义传入参数，记得当作数组取出，匿名传递有问题是不好溯源*/
    fun onClick(view: View, vararg params: Any) {
        this.params = params.toList()
        onClickListener?.invoke(view, this.params)
    }

    /** 长按事件触发，后续可以自定义传入参数，记得当作数组取出，匿名传递有问题是不好溯源*/
    fun onLongClick(view: View, vararg params: Any): Boolean {
        this.params = params.toList()
        return onLongClickListener?.invoke(view, this.params) ?: false
    }
}

typealias OnClick = (view: View, params: List<Any>) -> Unit
typealias OnLongClick = (view: View, params: List<Any>) -> Boolean